//
//  WLCaptcheButton.m
//  WLButtonCountingDownDemo
//
//  Created by 范智渊 on 16/1/14.
//  Copyright © 2016年 ZHWAYNE. All rights reserved.
//

#import "JMCaptcheButton.h"
#import "JMButtonCountdownManager.h"

@interface JMCaptcheButton ()

@property (nonatomic, strong) UILabel *overlayLabel;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic,strong)UIImageView *loadingImgV;

@end

@implementation JMCaptcheButton

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        _interval = 60;
        [self initialize];
    }
    
    return self;
}

// 开启定时器
- (void)startTimer {
    [self stopLoading];
    self.interval = 60;
    self.enabled             = NO;
    self.titleLabel.alpha    = 0;
    self.overlayLabel.alpha  = 1;
    [self.overlayLabel setBackgroundColor:self.disabledBackgroundColor ?: self.backgroundColor];
    [self.overlayLabel setTextColor:self.disabledTitleColor ?: self.titleLabel.textColor];
    self.overlayLabel.text = [NSString stringWithFormat:@"%lds", @(self.interval).intValue];
    
    // 如果定时器已经开启，则先停止再开启
    if (self.timer) [self stopTimer];
    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(setBtn) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    [self.timer fireDate];
    
}
// 关闭定时器
- (void)stopTimer {
    self.enabled             = YES;
    self.overlayLabel.alpha  = 0;
    self.titleLabel.alpha    = 1;
    [self.overlayLabel setBackgroundColor:self.backgroundColor];
    [self.overlayLabel setTextColor:self.titleLabel.textColor];
    [self.timer invalidate];
    self.timer = nil;
}
-(void)setBtn{
    
    self.interval -= 1;
    if (self.interval>0) {
        self.enabled             = NO;
        self.titleLabel.alpha    = 0;
        self.overlayLabel.alpha  = 1;
        [self.overlayLabel setBackgroundColor:self.disabledBackgroundColor ?: self.backgroundColor];
        [self.overlayLabel setTextColor:self.disabledTitleColor ?: self.titleLabel.textColor];
        self.overlayLabel.text = [NSString stringWithFormat:@"%lds", @(self.interval).intValue];
        if (self.interval==59) {
            if(self.countStartBlock!=nil){
                self.countStartBlock();
            }
        }
        if(self.countTimingBlock!=nil){
            self.countTimingBlock();
        }
        
    }else{
        if(self.countFinshBlock!=nil){
            self.countFinshBlock();
        }
       
        [self stopTimer];
    }
    
}

-(void)stopLoading{
    self.backgroundColor = UIColor.clearColor;
    self.loadingImgV.hidden = YES;
}
-(void)startLoading{
    self.loadingImgV.hidden = NO;
    self.backgroundColor = Button_UNABLE_BG_COLOR();
    
    [self.loadingImgV mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.centerY.equalTo(self);
        make.width.height.equalTo(@13);
    }];
    [self.loadingImgV setHidden:NO];
   

    delayOperation(0, ^{
        CALayer *loadingLayer = [CALayer layer];
        loadingLayer.bounds = CGRectMake(0, 0, self.loadingImgV.width, self.loadingImgV.height);
        loadingLayer.position = CGPointMake(self.loadingImgV.width / 2, self.loadingImgV.height / 2);
        loadingLayer.contents = (id)[UIImage imageNamed:@"button_loading"].CGImage; // 使用你自己的加载图片
        [self.loadingImgV.layer addSublayer:loadingLayer];
        
        CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        rotationAnimation.fromValue = [NSNumber numberWithFloat:0.0];
        rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
        rotationAnimation.duration = 2.0; // 旋转一圈所需的时间
        rotationAnimation.repeatCount = HUGE_VALF; // 无限循环
        [loadingLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
        self.enabled = NO;
        self.titleLabel.alpha    = 0;
    });
   
}
-(UIImageView *)loadingImgV{
    if(!_loadingImgV){
        _loadingImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, 13, 13))];
        _loadingImgV.contentMode = UIViewContentModeScaleAspectFill;
        _loadingImgV.centerX = self.width/2;
        _loadingImgV.centerY = self.height/2;
    }
    return _loadingImgV;
}
- (instancetype)init {
    if (self = [super init]) {
        _interval = 60;
        [self initialize];
    }
    
    return self;
}

- (void)dealloc {
    NSLog(@"***> %s [%@]", __func__, _identifyKey);
}

- (void)initialize {
    self.clipsToBounds      = YES;
    self.layer.cornerRadius = 4;
    self.opaque             = NO;
    
    [self addSubview:self.overlayLabel];
    [self addSubview:self.loadingImgV];
    _loadingImgV.hidden = YES;
}

- (UILabel *)overlayLabel {
    if (!_overlayLabel) {
        _overlayLabel                 = [UILabel new];
        _overlayLabel.textColor       = self.titleLabel.textColor;
        _overlayLabel.backgroundColor = self.backgroundColor;
        _overlayLabel.font            = self.titleLabel.font;
        _overlayLabel.textAlignment   = NSTextAlignmentRight;
        _overlayLabel.alpha           = 0;
        _overlayLabel.opaque           = NO;
    }
    
    return _overlayLabel;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.overlayLabel.frame = self.bounds;

}


//- (void)shouldCountDown {
//    
//    __weak __typeof(self) weakSelf = self;
//    [[JMButtonCountdownManager defaultManager] scheduledCountDownWithKey:self.identifyKey timeInterval:self.interval countingDown:^(NSTimeInterval leftTimeInterval) {
//        __strong __typeof(weakSelf) self = weakSelf;
//        
//        self.enabled             = NO;
//        self.titleLabel.alpha    = 0;
//        self.overlayLabel.alpha  = 1;
//        [self.overlayLabel setBackgroundColor:self.disabledBackgroundColor ?: self.backgroundColor];
//        [self.overlayLabel setTextColor:self.disabledTitleColor ?: self.titleLabel.textColor];
//        self.overlayLabel.text = [NSString stringWithFormat:@"%@s", @(leftTimeInterval)];
//        if(self.countStartBlock!=nil&&leftTimeInterval==self.interval){
//            self.countStartBlock();
//        }
//        if(self.countTimingBlock!=nil){
//            self.countTimingBlock();
//        }
//    } finished:^(NSTimeInterval finalTimeInterval) {
//        __strong __typeof(weakSelf) self = weakSelf;
//        if(self.countFinshBlock!=nil){
//            self.countFinshBlock();
//        }
//        self.enabled             = YES;
//        self.overlayLabel.alpha  = 0;
//        self.titleLabel.alpha    = 1;
//        [self.overlayLabel setBackgroundColor:self.backgroundColor];
//        [self.overlayLabel setTextColor:self.titleLabel.textColor];
//    }];
//}

- (void)sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    if (![[self actionsForTarget:target forControlEvent:UIControlEventTouchUpInside] count]) {
        return;
    }
    
    [super sendAction:action to:target forEvent:event];
}

- (void)fire {
//    [self shouldCountDown];
    [self startTimer];
}

@end
